package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.service.impl.ArticleServiceImpl;
import com.example.forum.service.impl.BoardServiceImpl;
import com.example.forum.service.impl.UserServiceImpl;
import com.example.forum.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api("文章接口")
@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {

    @Autowired
    private ArticleServiceImpl articleService;



    @ApiOperation("添加文章")
    @RequestMapping("/create")
    public AppResult create(@ApiParam("必传参数有board_id,content,title") Article article, HttpServletRequest request) {
        if(!StringUtils.hasLength(article.getContent()) ||
                !StringUtils.hasLength(article.getTitle()) ||
                article.getBoard_id() < 0) {
            log.error("Article相关参数校验失败");
            log.error("更新board文章数失败");
            return AppResult.fail("Article相关参数校验失败");
        }
        Long userId = Long.valueOf(JWTUtils.getUserId(request.getHeader("user_token")));
        article.setUser_id(userId);
        Integer ret1 = articleService.insertSelective(article);
        if(ret1 < 0 || ret1 == null) {
            log.error("Article插入失败");
            return AppResult.fail("Article插入失败");
        }

        return AppResult.success("文章插入成功");
    }


    @ApiOperation("获取帖子列表")
    @RequestMapping("/getAllByBoardId")
    public AppResult getAllByBoardId(@RequestParam(value = "boardId",required = false) @ApiParam("论坛板块id") Long board_id) {
        List<Article> articles = null;
        if(board_id == null) {
            articles = articleService.selectAllByBoardId();
        }else {
            articles = articleService.selectByBoardId(board_id);
        }
        for(Article article : articles) {
            String pathName = article.getUser().getAvatar_url();
            if(pathName != null) {
                Integer i = pathName.indexOf("image");
                if (i == null) {
                    log.warn(ResultCode.FAILED_NOT_EXISTS.getMessage());
                    throw new ApplicationException(ResultCode.FAILED_NOT_EXISTS.getMessage());
                }
                article.getUser().setAvatar_url("./" + pathName.substring(i));
            }
        }
        log.info("查找成功");
        return AppResult.success(articles);
    }

    @ApiOperation("获取详细文章")
    @RequestMapping("/details")
    public AppResult details(HttpServletRequest request,
                            @RequestParam("id") @ApiParam("文章id") @NonNull Long id) {
        Article article = articleService.selectArticle(id);
        if(article == null) {
            return AppResult.fail("文章不存在");
        }

        String stringUserId = JWTUtils.getUserId(request.getHeader("user_token"));
        Long userId = Long.parseLong(stringUserId);
        if(userId.equals(article.getUser_id())) {
            article.setIs_author(true);
        }
        log.info("查找文章成功");
        return AppResult.success(article);
    }

    @ApiOperation("点赞")
    @RequestMapping("/thumbsUp")
    public AppResult thumbsUp(@RequestParam("id") @ApiParam("文章id") @NonNull Long articleId) {
        Article article = articleService.updateLikeCount(articleId);
        if(article == null) {
            return AppResult.fail("文章不存在");
        }
        log.info("更改点赞数成功");
        return AppResult.success(article);
    }

    @ApiOperation("取消点赞")
    @RequestMapping("/riseUp")
    public AppResult riseUp(@RequestParam("id") @ApiParam("文章id") @NonNull Long articleId) {
        Article article = articleService.updateCountRise(articleId);
        if(article == null) {
            return AppResult.fail("文章不存在");
        }
        log.info("更改点赞数成功");
        return AppResult.success(article);
    }

    @ApiOperation("删除文章")
    @RequestMapping("/delete")
    public AppResult delete(@RequestParam("id") @ApiParam("文章id") @NonNull Long articleId) {
        Integer ret = articleService.deleteArticleById(articleId);
        if(ret == null) {
            return AppResult.fail("文章删除失败");
        }
        return AppResult.success("文章删除成功");

    }


    @ApiOperation("更新文章")
    @RequestMapping("/modify")
    public AppResult modify(@RequestParam("id") @ApiParam("文章id") @NonNull Long id,
                            @RequestParam("content") @ApiParam("正文")String content,
                            @RequestParam("title") @ApiParam("标题")String title) {
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        Integer ret = articleService.updateArticle(article);
        if(ret == null || ret <= 0) {
            return AppResult.fail("更新文章失败");
        }
        return AppResult.success("更新文章成功");

    }


    @ApiOperation("根据userId获取所有文章")
    @RequestMapping("/getAllByUserId")
    public AppResult getAllByUserId(@RequestParam(value = "userId",required = false) @ApiParam("用户id") Long userId,
                                    HttpServletRequest request) {
        Long id = null;
        if(userId == null) {
            String stringUserId = JWTUtils.getUserId(request.getHeader("user_token"));
            id = Long.parseLong(stringUserId);
        }else {
            id = userId;
        }
        List<Article> lists = articleService.selectArticleByUserId(id);
        return AppResult.success(lists);
    }


}
